package com.tiantian.web.controller.mail;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.tiantian.common.annotation.Log;
import com.tiantian.common.core.domain.ResponseResult;
import com.tiantian.common.core.domain.entity.SysUser;
import com.tiantian.common.enums.BusinessType;
import com.tiantian.framework.config.properties.MailProperties;
import com.tiantian.system.domain.dto.MailRequestDTO;
import com.tiantian.system.service.EmailService;
import com.tiantian.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 邮件发送
 *
 * @author TianTian
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/mail")
public class MailController {


    private final MailProperties mailProperties;
    private final ISysUserService userService;
    private final EmailService emailService;

    /**
     * 发送简单文字邮件
     *
     * @param mailRequestDTO 参数
     */
    @PostMapping("/sendAll")
    @SaCheckPermission("mail")
    @Log(title = "发送邮件", businessType = BusinessType.EMAIL, isSaveResponseData = false)
    public ResponseResult<Void> sendAll(@RequestBody @Valid MailRequestDTO mailRequestDTO) {
        if (!mailProperties.getEnabled()) {
            return ResponseResult.fail("当前系统没有开启邮箱功能!");
        }
        // 群发
        emailService.sendAllEmail(mailRequestDTO);
        return ResponseResult.ok();
    }

    // 获取系统内所有新人用户的邮件并附上姓名
    @GetMapping("/all")
    @SaCheckPermission("mail")
    public ResponseResult<List<Map<String, String>>> getSystemAllEmail(){
        List<Map<String, String>> ajax = new ArrayList<>();
        List<SysUser> sysUsers = userService.selectPageUserList(null);
        for (SysUser user : sysUsers) {
            Map<String, String> map = new HashMap<>();
            map.put("email",user.getEmail());
            map.put("nickName",user.getNickName());
            ajax.add(map);
        }
        return ResponseResult.ok(ajax);
    }


}
